//
//  SessionManager.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/26.
//

#import "SessionManager.h"

@implementation SessionManager

+ (SessionManager *)sharedInstance
{
    static SessionManager * _instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[SessionManager alloc] init];
    });
    return _instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.requestSerializer.timeoutInterval = TIME_REQUEST_OUT;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setValueForHTTPHeaderFieldWithUrl:@""];
        });
    }
    return self;
}

- (void)setValueForHTTPHeaderFieldWithUrl:(NSString *)url{
    [self.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    self.requestSerializer  = [AFJSONRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    // 登录接口返回的token，若用户未登录，为空字符串
    if ([url rangeOfString:GET_DOMAIN].location != NSNotFound) {
        // 域名检查接口 - 不需要传参数token
    } else {
        if(isStr(readStr([GlobalData sharedInstance].Global_Token))){
            [self.requestSerializer setValue:readStr([GlobalData sharedInstance].Global_Token) forHTTPHeaderField:KEY_x_auth_token];
        }
    }
    NSString *currentVersion = [GlobalMethod getVersion];
    [self.requestSerializer setValue:currentVersion forHTTPHeaderField:KEY_x_version];
    NSString * bundleIdentifier = [GlobalMethod getBundleIdentifier];
    [self.requestSerializer setValue:bundleIdentifier forHTTPHeaderField:KEY_x_package_name];
    // adid
    [self.requestSerializer setValue:[GlobalMethod getAdid] forHTTPHeaderField:KEY_x_adid];
    // 经纬度
    CLLocationCoordinate2D currentLocation = [[LocationService sharedInstance] getCurrentLocation];
    NSString * lat = @"";
    if (currentLocation.latitude != 0) {
        lat = [NSString stringWithFormat:@"%f", currentLocation.latitude];
    }
    NSString * lon = @"";
    if (currentLocation.longitude != 0) {
        lon = [NSString stringWithFormat:@"%f", currentLocation.longitude];
    }
    [self.requestSerializer setValue:readStr(lat) forHTTPHeaderField:KEY_x_latitude];
    [self.requestSerializer setValue:readStr(lon) forHTTPHeaderField:KEY_x_longitude];
    
    // 配置证书
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode: AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = true; //允许无效证书
    [securityPolicy setValidatesDomainName: false];
    self.securityPolicy = securityPolicy;
    
    
}

@end
